package com.example.admin.service.impl;

import com.example.admin.model.Permission;
import com.example.admin.model.Role;
import com.example.admin.repository.PermissionRepository;
import com.example.admin.repository.RoleRepository;
import com.example.admin.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleRepository roleRepository;
    
    @Autowired
    private PermissionRepository permissionRepository;

    @Override
    public List<Role> findAll() {
        return roleRepository.findAll();
    }

    @Override
    public Role findById(Long id) {
        return roleRepository.findById(id).orElse(null);
    }

    @Override
    public Role save(Role role) {
        if (role.getPermissions() != null) {
            Set<Permission> managedPermissions = new HashSet<>();
            for (Permission perm : role.getPermissions()) {
                Optional<Permission> existing = permissionRepository.findByName(perm.getName());
                if (existing.isPresent()) {
                    managedPermissions.add(existing.get());
                } else {
                    managedPermissions.add(permissionRepository.save(perm));
                }
            }
            role.setPermissions(managedPermissions);
        }
        return roleRepository.save(role);
    }

    @Override
    public void deleteById(Long id) {
        roleRepository.deleteById(id);
    }
}
